import { useNavigate } from 'react-router-dom'
import { DragEvent } from 'react'

export default (category: CategoryType) => {
  const navigate = useNavigate()

  const updateContentCategory = async (category_id: number, id: number) => {
    await window.api.sql(`update contents set category_id=@category_id where id=@id`, 'update', {
      category_id,
      id
    })

    navigate(`/config/category/contentList/${category_id}/content/${id}`)
  }

  // 拖拽相关hooks
  const dragHandle = {
    onDragOver: (e: DragEvent) => {
      // 阻止默认行为，允许放置,不然onDrop事件不能触发
      e.preventDefault()
      // 修改默认拖拽样式
      e!.dataTransfer!.dropEffect = 'move'
      const el = e.currentTarget as HTMLDivElement
      el.classList.add('drag-over')
    },
    onDragLeave: (e: DragEvent) => {
      const el = e.currentTarget as HTMLDivElement
      el.classList.remove('drag-over')
    },
    onDrop: (e: DragEvent) => {
      const el = e.currentTarget as HTMLDivElement
      el.classList.remove('drag-over')
      // 拿到拖拽过来的id
      const id = +e!.dataTransfer!.getData('id')
      updateContentCategory(category.id, id)
    }
  }

  return { dragHandle }
}
